import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:scan_gun/scan_gun.dart';
import 'package:toast/toast.dart';

import 'tallymodel.dart';

class TallyLpnScreen extends StatelessWidget {
  TallyQr data;

  TallyLpnScreen({this.data});

  @override
  Widget build(BuildContext context) {
    return TallyLpnScreenPage(data: data);
  }
}

class TallyLpnScreenPage extends StatefulWidget {
  TallyQr data;

  TallyLpnScreenPage({this.data});

  @override
  _TallyLpnScreenPageState createState() => _TallyLpnScreenPageState(tallyQr: data);
}

class _TallyLpnScreenPageState extends BaseState<TallyLpnScreenPage> {
  TallyQr tallyQr;
  List<TallyLPN> data = new List();

  _TallyLpnScreenPageState({this.tallyQr});

  @override
  String setTitle({String title}) {
    return "Tally:LPN";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    next = "Submit";
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15, right: 15),
            child: Row(
              children: [
                Text(
                  "Container NO#: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.getStringisEmpty(tallyQr.container_no),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 2),
            child: Row(
              children: [
                Text(
                  "Uniq ID: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.getStringisEmpty(tallyQr.inboundNo),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 2),
            child: Row(
              children: [
                Text(
                  "SKU/Barcode: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.getStringisEmpty(tallyQr.sku),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 2),
            child: Row(
              children: [
                Text(
                  "CTN: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Expanded(
                  child: Text(
                    Utils.getStringisEmpty("${tallyQr.ctnQty}"),
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
                Visibility(
                  visible: tallyQr.pcsQty > 0 ? true : false,
                  child: Text(
                    "PCS: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ),
                Visibility(
                  visible: tallyQr.pcsQty > 0 ? true : false,
                  child: Expanded(
                    child: Text(
                      Utils.getStringisEmpty("${tallyQr.pcsQty}"),
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  getLpnTallySku();
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        getLpnTallySku();
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan inbound lpn barcode",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          SizedBox(
            height: 10,
          ),
          Container(
            margin: const EdgeInsets.only(left: 15, top: 10, right: 0, bottom: 0),
            width: double.infinity,
            child: Text(
              'Submitted in',
              style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 15, top: 2, right: 15, bottom: 0),
            child: Row(
              children: <Widget>[
                Expanded(
                    flex: 1, //设置权重
                    child: Text(
                      'SKU',
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    )),
                Expanded(
                    flex: 1, //设置权重
                    child: Text(
                      'QTY',
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    )),
              ],
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 10),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        TallyLPN tallyLPN = data[index];
        print("index:${index}");
        return Column(
          children: [
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1, //设置权重
                    child: Text(
                      Utils.getStringisEmpty(tallyLPN.sku),
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    )),
                Expanded(
                    flex: 1, //设置权重
                    child: Text(
                      "${tallyLPN.quantity}",
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    )),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(code)) {
      Toast.show("scan inbound lpn", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    tallyQr.ibLpn = code;
    checkSku(tallyQr);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  void getLpnTallySku() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    Map<String, dynamic> map = new HashMap();
    map["warehousingNotifyId"] = tallyQr.notifyId;
    map["type"] = tallyQr.type;
    map["lpn"] = code;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.getLpnTallySku, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        data = (new List<dynamic>.from(baseResponse.data).map((userJson) => TallyLPN.fromJson(userJson)).toList());
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }


  void checkSku(TallyQr tallyQr) async {

    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }


    try {
      String json = jsonEncode(tallyQr);
      BaseResponse baseResponse = await NetworkManager().request(context, Constants.tallySubmit, method: BaseMethod.post, data: json);
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
      if (baseResponse.status == 200) {
        Navigator.of(context).pop(true);
      } else {
        ToastContext().init(context);
        Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
      }
    } catch (e) {
      e.toString();
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    }


  }

}
